<?php
/**
 * Created by PhpStorm.
 * User: 元曦
 * Date: 2023-02-22
 * Time: 9:45:22
 * Info: 内容模型模型
 */

namespace app\common\model;

use think\facade\Db;
use libs\Form;

class ModelsField extends TimeInit
{

    const FORM_FIELDS = [
        1  => '单行文本',
        2  => '多行文本',
        3  => '单选按钮',
        4  => '多选按钮',
        5  => '单图上传',
        6  => '多图上传',
        7  => '下拉选择',
        8  => '附件上传',
        9  => '日期选择',
        10 => '编辑器',
        11 => '编辑器mini',
    ];

    /**
     * 获取模型列表
     */
    public static function getModelList($params = [])
    {
        $data = [];
        if ($params) {
            $limit = $params['limit'];
            $first = $params['first'];
            $field = $params['field'] ?: 'sorting';
            $order = $params['order'] ?: 'asc';
            $key   = $params['key'];
            //获取sql条件
            $where = function ($query) use ($key) {
                if ( ! empty($key['name'])) {
                    $query->whereLike('name', '%'.$key['name'].'%');
                }
                if ( ! empty($key['model_id'])) {
                    $query->where('model_id', $key['model_id']);
                }
                if (isset($key['status']) && $key['status'] != '') {
                    $query->where('status', $key['status']);
                }
            };
        }
        $count = ModelsField::where($where)->count();
        $list  = ModelsField::where($where)->limit($first, $limit)->order($field, $order)->select();
        foreach ($list as $k => $v) {
            $v['model_name'] = Models::where('id', $v['model_id'])->value('name as model_name');
            $v['type']       = self::FORM_FIELDS[$v['type']] ?? '';
        }
        $data['list']  = $list ?? [];
        $data['count'] = $count ?? 0;

        return $data;
    }

    /**
     * 根据模型id输出对应的扩展字段 html
     *
     * @param $model_id
     *
     * @return string
     */
    public static function getModelFields($model_id, $contentExt = [])
    {
        $modelInfo = self::where([
            'model_id' => $model_id,
            'status'   => 1
        ])->order('sort asc,id asc')->select()->toArray();

        $string = '';
        foreach ($modelInfo as $v) {
            $v['name_short'] = $v['name'];
            $v['name']       = "ext[".$v['name']."]";
            $verify          = '';
            if ($v['is_required']) {
                $verify = 'lay-verify="required"';
            }
            $fieldType = $v['type'];
            $str       = '';
            if ($fieldType == 1) {
                //单行文本输入
                $value = $contentExt[$v['name_short']] ?? '';
                $str   = '<input type="text" name="'.$v['name'].'" '.$verify.' autocomplete="off" placeholder="请输入'.$v['title'].'" value="'.$value.'"  class="layui-input">';
            } elseif ($fieldType == 2) {
                //多行文本输入
                $value = $contentExt[$v['name_short']] ?? '';
                $str   = '<textarea name="'.$v['name'].'" class="layui-textarea" '.$verify.' placeholder="请输入'.$v['title'].'">'.$value.'</textarea>';
            } elseif ($fieldType == 3) {
                //单选按钮
                $value    = $contentExt[$v['name_short']] ?? '';
                $valueArr = json_decode($v['value'], true);
                foreach ($valueArr as $kv => $nv) {
                    if ($kv == 0 || isset($nv['value']) && $value == $nv['value']) {
                        $ckecked = 'checked';
                    } else {
                        $ckecked = '';
                    }
                    $str .= '<input type="radio" name="'.$v['name'].'" value="'.$nv['value'].'" title="'.$nv['name'].'" '.$verify.' '.$ckecked.'>';
                }
            } elseif ($fieldType == 4) {
                //多选
                $vauleData = '';
                if ( ! empty($contentExt[$v['name_short']])) {
                    $vauleData = explode(',', $contentExt[$v['name_short']]);
                }
                $valueArr = json_decode($v['value'], true);
                foreach ($valueArr as $kv => $nv) {
                    $ckecked = '';
                    if ( ! empty($vauleData)) {
                        if (in_array($nv['value'], $vauleData)) {
                            $ckecked = 'checked';
                        }
                    }
                    $str .= '<input name="'.$v['name_short'].'" type="hidden"><input type="checkbox" name="'.$v['name'].'[]" value="'.$nv['value'].'" lay-skin="primary" title="'.$nv['name'].'" '.$ckecked.'>';
                }
            } elseif ($fieldType == 5) {
                //单图上传
                $required = "";
                if ($v['is_required']) {
                    $required = "required";
                }
                $value  = $contentExt[$v['name_short']] ?? '';
                $picUrl = url('upload_file/index', ['type' => 'one', 'select_id' => $v['name_short'].'-select-input']);
                $string .= '<div class="layui-form-item huicmf-upload">';
                $string .= '<label class="layui-form-label '.$required.'">'.$v['title'].'</label>';
                $string .= '<div class="layui-input-block">';
                $string .= '<input type="text" name="'.$v['name'].'" '.$verify.' value="'.$value.'" onmouseover="hui_img_preview(\''.$v['name_short'].'-select-input\',this.value)" onmouseout="layer.closeAll();" id="'.$v['name_short'].'-select-input" autocomplete="off" class="layui-input">';
                $string .= '<button type="button" class="layui-btn layui-btn-normal layUpload" id="pic_'.$v['name_short'].'"
                            data-multiple="false" data-input-id="'.$v['name_short'].'-select-input"
                            data-preview-id="'.$v['name_short'].'" data-type="image"><i class="layui-icon"></i>上传图片
                    </button>';
                $string .= '<button type="button" class="layui-btn ml-10" data-open-pic="'.$picUrl.'"><i class="layui-icon"></i>选择图片</button>';
                $string .= '</div>';
                $string .= '<div class="layui-form-label"></div>
                <div class="layui-input-inline">
                    <div id="'.$v['name_short'].'-select-input_box" class="pic_box"></div>
                </div>';
                $string .= '</div>';
            } elseif ($fieldType == 6) {
                //多图上传
                $value     = $contentExt[$v['name_short']] ?? '';
                $valueData = [];
                if ( ! empty($value)) {
                    $valueData = explode(',', $value);
                }

                $picNums = get_config('pic_more_nums');
                $picUrl  = url('upload_file/index',
                    ['type' => 'more', 'select_id' => $v['name_short'].'-uploader-list']);
                $string  .= '<div class="layui-form-item huicmf-upload">';
                $string  .= '<input name="'.$v['name_short'].'" type="hidden">';
                $string  .= '<label class="layui-form-label">多图选择</label>';
                $string  .= '<div class="layui-input-block">
                    <a class="layui-btn"
                       data-open-pic="'.$picUrl.'"><i class="layui-icon">&#xe67c;</i>选择图片</a>
                </div>';
                $string  .= '<tip>(可拖拽图片调整显示顺序 )</tip>';
                $string  .= '<div class="layui-input-block">';
                $string  .= '<div class="uploader-list am-cf" id="'.$v['name_short'].'-uploader-list" data-name="'.$v['name'].'[]" data-nums="'.$picNums.'">';
                if ( ! empty($valueData)) {
                    foreach ($valueData as $kd => $vd) {
                        $string .= '<div class="file-item file-item-id-'.$kd.'">';
                        $string .= '<img src="'.$vd.'">';
                        $string .= '<input type="hidden" name="'.$v['name'].'[]" value="'.$vd.'">';
                        $string .= '<i class="layui-icon layui-icon-close file-item-delete" onclick="fileItemDelete(\''.$kd.'\')"></i>';
                        $string .= '</div>';
                    }
                }
                $string .= '</div>';
                $string .= '</div>';
                $string .= '</div>';
            } elseif ($fieldType == 7) {
                //下拉选择
                $value    = $contentExt[$v['name_short']] ?? '';
                $valueArr = json_decode($v['value'], true);
                $str      = '<select name="'.$v['name'].'" '.$verify.'><option value="">请选择'.$v['title'].'</option>';
                foreach ($valueArr as $kv => $nv) {
                    $selected = '';
                    if ($nv['value'] == $value) {
                        $selected = 'selected';
                    }
                    $str .= '<option value="'.$nv['value'].'" '.$selected.'>'.$nv['name'].'</option>';
                }
                $str .= '</select>';
            } elseif ($fieldType == 8) {
                //附件上传

            } elseif ($fieldType == 9) {
                //日期选择
                $value = $contentExt[$v['name_short']] ?? '';
                if ( ! empty(substr($value, 0, 10))) {
                    if (substr($value, 0, 10) == '0000-00-00') {
                        $value = '';
                    }
                }
                if ($v['value'] == 2) {
                    $placeholder = 'yyyy-MM-dd HH:mm:ss';
                } else {
                    $placeholder = 'yyyy-MM-dd';
                }
                $str = '<input class="layui-input" type="text" name="'.$v['name'].'"  id="date-'.$v['name_short'].'" value="'.$value.'" autocomplete="off" placeholder="'.$placeholder.'" style="width:220px">';
                $str .= '<script>';
                $str .= 'laydate.render({';
                $str .= "elem: '#date-".$v['name_short']."'";
                if ($v['value'] == 2) {
                    $str .= ",type: 'datetime'";
                } else {
                    $str .= ",type: 'date'";
                }
                $str .= "});";
                $str .= '</script>';
            } elseif ($fieldType == 10) {
                //富文本编辑器
                $value = ! empty($contentExt[$v['name_short']]) ? htmlspecialchars_decode($contentExt[$v['name_short']]) : '';
                $str   = '<input name="'.$v['name_short'].'" type="hidden">';
                $str   .= Form::editor($v['name'], $v['name_short'], $value, 'height:280px;');
            } elseif ($fieldType == 11) {
                //富文本编辑器mini
                $value = ! empty($contentExt[$v['name_short']]) ? htmlspecialchars_decode($contentExt[$v['name_short']]) : '';
                $str   = '<input name="'.$v['name_short'].'" type="hidden">';
                $str   .= Form::editorMini($v['name'], $v['name_short'], $value, 'height:280px;');
            } else {
                $str = "";
            }
            if ($fieldType != 5 && $fieldType != 6) {
                $string .= self::tag_start($v['title'], $v['is_required']);
                $string .= $str;
                $string .= self::tag_end();
            }
        }

        return $string;
    }

    /**
     * html输出开始标签
     *
     * @param $title
     * @param $isRequired
     *
     * @return string
     */
    private static function tag_start($title, $isRequired = 0)
    {
        $required = "";
        if ($isRequired) {
            $required = "required";
        }
        $html = '';
        $html .= '<div class="layui-form-item">';
        $html .= '<label class="layui-form-label '.$required.'">'.$title.'</label>';
        $html .= '<div class="layui-input-block">';

        return $html;
    }

    /**
     * html输出结束标签
     * @return string
     */
    private static function tag_end()
    {
        return '</div></div>';
    }

}
